package com.example.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用Buffer和Channel输入内容
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
        File file = new File("d:\\1.txt");
        // 文件输入流，底层实现写出的流还是InputStream的实现
        // 获取FileInputStream的Channel对象，使用fileChannel和byteBuffer操作文件
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel inputStreamChannel = fileInputStream.getChannel();

        // 将buffer中的数据读取到文件中
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\2.txt");
        FileChannel outputStreamChannel = fileOutputStream.getChannel();

        // 通过文件channel将数据读取到缓存中
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {
            // 属性重置
            byteBuffer.clear();
            int read = inputStreamChannel.read(byteBuffer);
            if (read == -1) {
                break;
            }
            // 读写模式切换(position和limit 数值互换)
            byteBuffer.flip();
            outputStreamChannel.write(byteBuffer);
        }

        // 关闭流
        fileInputStream.close();
        fileOutputStream.close();

    }
}
